package cn.iocoder.yudao.module.engine.service.core.filter.read.deprecated;

import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.util.StrUtil;
import cn.iocoder.yudao.framework.common.util.json.JsonUtils;
import cn.iocoder.yudao.module.engine.enums.EnumAudioType;
import cn.iocoder.yudao.module.engine.model.config.ThreeAxisSensorFrequencyConfig;
import cn.iocoder.yudao.module.engine.model.context.ControlEngineContext;
import cn.iocoder.yudao.module.engine.model.context.SensorStatusContext;
import cn.iocoder.yudao.module.engine.model.engine.EngineInputData;
import cn.iocoder.yudao.module.engine.service.core.filter.read.base.AbstractThreeAxisSensor2AudioFilter;
import cn.iocoder.yudao.module.engine.service.log.IEngineLogService;
import cn.iocoder.yudao.module.infra.api.config.IConfigApi;
import jakarta.annotation.Resource;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;

import java.math.BigDecimal;
import java.util.List;

@Deprecated
@Slf4j
@Component
public class ThreeAxisSensorFrequency2AudioFilter extends AbstractThreeAxisSensor2AudioFilter {
    private static final String CONFIG_KEY_FREQUENCY = "sensor.three_axis.frequency";

    @Resource
    private IConfigApi configApi;

    @Resource
    private IEngineLogService logService;

    @Override
    public EnumAudioType getAudioType() {
        return EnumAudioType.THREE_AXIS_HIGH;
    }

    @Override
    public List<String> triggerThreeAxisSensor(ControlEngineContext engineContext,
                                               EngineInputData.Sensor sensor) {
        final SensorStatusContext.TreeAxisFrequency status = engineContext.getSynStatusCtx().getSensorStatusContext().getTreeAxisFrequency();
        final Integer upCount = sensor.getUpCount();
        if (upCount == null) {
            throw new IllegalArgumentException("upCount不能为空");
        }

        final int changeUpCount = getChangeValue(status, upCount);

        try {
            final Long firstReceiveTime = status.getFirstReceiveTime();
            if (firstReceiveTime == 0) {
                log.info("三轴传感器-首次接收到信号");
                return null;
            }

            final String frequencyConfigString = configApi.getValueByKey(CONFIG_KEY_FREQUENCY);
            final ThreeAxisSensorFrequencyConfig frequencyConfig = JsonUtils.parseObject(frequencyConfigString, ThreeAxisSensorFrequencyConfig.class);
            final Integer startTriggerSeconds = frequencyConfig.getStartTriggerSeconds();

            final long duration = (System.currentTimeMillis() - firstReceiveTime) / 1000;
            if (duration < startTriggerSeconds) {
                log.info("三轴传感器-未触发首次, duration = {}, startTriggerSeconds = {}", duration, startTriggerSeconds);
                return null;
            }

            if (!status.getStartTrigger()) {
                status.setStartTrigger(true);
                log.info("三轴传感器-开始触发, duration = {}, startTriggerSeconds = {}", duration, startTriggerSeconds);
                logService.log(engineContext, StrUtil.format("【三轴传感器已触发高潮响应】开始触发, [当前变动次数]: {}, [最大变动次数]: {}",
                        changeUpCount, status.getMaxChangeUpCount()));
                return frequencyConfig.getStartTriggerTags();
            }

            final List<ThreeAxisSensorFrequencyConfig.TriggerConfig> triggers = frequencyConfig.getTriggers();
            if (CollUtil.isEmpty(triggers)) {
                log.warn("三轴传感器-触发器配置为空");
                return null;
            }

            triggers.sort((o1, o2) -> o2.getTriggerPercent().compareTo(o1.getTriggerPercent()));
            final float currentPercent = status.getMaxChangeUpCount() != 0 ? changeUpCount * 1f / status.getMaxChangeUpCount() : 0;

            ThreeAxisSensorFrequencyConfig.TriggerConfig targetTrigger = null;
            for (ThreeAxisSensorFrequencyConfig.TriggerConfig postTrigger : triggers) {
                if (new BigDecimal(currentPercent).compareTo(new BigDecimal(postTrigger.getTriggerPercent())) > 0) {
                    targetTrigger = postTrigger;
                    break;
                }
            }

            if (targetTrigger != null) {
                final boolean hasTriggered = status.getTriggerId4Triggered().getOrDefault(targetTrigger.getTriggerId(), false);
                if (hasTriggered) {
                    log.info("三轴传感器-已触发多次, currentPercent = {}, triggerPercent = {}, changeUpCount = {}, maxChangeUpCount = {}",
                            currentPercent, targetTrigger.getTriggerPercent(), changeUpCount, status.getMaxChangeUpCount());
                    logService.log(engineContext, StrUtil.format("【三轴传感器已触发】已触发多次, [当前百分比]: {}, [触发百分比]: {}, [当前变动次数]: {}, [最大变动次数]: {}",
                            currentPercent, targetTrigger.getTriggerPercent(), changeUpCount, status.getMaxChangeUpCount()));
                    return targetTrigger.getPostTriggerTags();
                } else {
                    status.getTriggerId4Triggered().put(targetTrigger.getTriggerId(), true);
                    log.info("三轴传感器-已触发首次, currentPercent = {}, triggerPercent = {}, changeUpCount = {}, maxChangeUpCount = {}",
                            currentPercent, targetTrigger.getTriggerPercent(), changeUpCount, status.getMaxChangeUpCount());
                    logService.log(engineContext, StrUtil.format("【三轴传感器已触发】已触发首次, [当前百分比]: {}, [触发百分比]: {}, [当前变动次数]: {}, [最大变动次数]: {}",
                            currentPercent, targetTrigger.getTriggerPercent(), changeUpCount, status.getMaxChangeUpCount()));
                    return targetTrigger.getFirstTriggerTags();
                }
            }

            log.info("三轴传感器-未触发, currentPercent = {}, changeUpCount = {}, maxChangeUpCount = {}",
                    currentPercent, changeUpCount, status.getMaxChangeUpCount());
            logService.log(engineContext, StrUtil.format("【三轴传感器未触发】 [当前百分比]: {}, [当前变动次数]: {}, [最大变动次数]: {}",
                    currentPercent, changeUpCount, status.getMaxChangeUpCount()));
            return null;
        } finally {
            if (changeUpCount > status.getMaxChangeUpCount()) {
                status.setMaxChangeUpCount(changeUpCount);
            }

            if (status.getFirstReceiveTime() == 0) {
                status.setFirstReceiveTime(System.currentTimeMillis());
            }

            if (status.getLastTriggerTime() == 0) {
                status.setLastTriggerTime(System.currentTimeMillis());
            }

            status.setLastTriggerUpCount(upCount);

            engineContext.getSynStatusCtx().syn();
        }
    }

    private static int getChangeValue(SensorStatusContext.TreeAxisFrequency status, Integer upCount) {
        if (status.getLastTriggerUpCount() != 0) {
            int durationSeconds = (int) ((System.currentTimeMillis() - status.getLastTriggerTime()) / 1000);
            if (durationSeconds == 0) {
                durationSeconds = 1;
            }
            final int dif = (upCount - status.getLastTriggerUpCount()) * 10 / durationSeconds;
            return dif;
        } else {
            return 0;
        }
    }

}
